#include "musiclist.h"
#include<QMimeDatabase>
#include<QDebug>
#include<QSqlQuery>
#include<QSqlError>
void MusicList::addMusicByUrl(const QList<QUrl> &urls)
{
    for(auto musicUrl : urls)
    {

        QString Path=musicUrl.toLocalFile();
        if(musicPaths.contains(Path))
         continue;
        musicPaths.insert(Path);

    // 筛选出⾳乐⽂件
    QMimeDatabase db;
    QMimeType mime = db.mimeTypeForFile(musicUrl.toLocalFile());
    // 获取文件的 MIME 类型
     if(mime.name() == "audio/mp3" || mime.name() == "audio/flac" || mime.name() == "audio/wav") {
      qDebug() << "Failed to filter music file, MIME type:" << (mime.isValid() ? mime.name() : "unknown");
     continue;
           }
    //⾳乐⽂件，加⼊歌曲列表


    musicList.push_back(musicUrl);

    qDebug()<<"add musiclist file count is :"<<musicList.size();

    //auto it=musicList.front().getMusicId();
      //qDebug()<<"musicid is "<<it;
    }
}

MusicList::MusicList()
{

}

MusicList::iterator MusicList::begin()
{
    return musicList.begin();
}

MusicList::iterator MusicList::end()
{
    return musicList.end();
}

MusicList::iterator MusicList::findMusicById(const QString &musicId)
{
    for(iterator it=musicList.begin();it!=musicList.end();++it)
    {


        if(it->getMusicId()==musicId)
        {
            qDebug()<<"find musicid :"<<musicId;
            return it;
        }
    }
     qDebug()<<" No find musicid :"<<musicId;
     return musicList.end();
}

void MusicList::writeToDB()
{
     qDebug()<<"writeToDB musicsize :"<<musicList.size();
    for(auto e:musicList)
    {
       qDebug()<<"writeToDB :"<<e.getMusicId();
       e.insertMusicToDB();
    }
}

void MusicList::readFromDB()
{
    QString sql("select musicId, musicName, musicSinger, albumName,duration, musicUrl, isLike, isHistory from MUSICS");
      QSqlQuery query;
       if(!query.exec(sql))
      {
                qDebug()<<"数据库查询失败";
                return;
      }
while(query.next())
{
    Music music;
    music.setMusicId(query.value(0).toString());
    music.setMusicName(query.value(1).toString());
    music.setSingerName(query.value(2).toString());
    music.setAlbumName(query.value(3).toString());
    music.setDuration(query.value(4).toLongLong());
    music.setMusicUrl("file:///"+query.value(5).toString());
    music.setIsLike(query.value(6).toBool());
    music.setIsHistory(query.value(7).toBool());

      musicList.push_back(music);
      musicPaths.insert(music.getMusicUrl().toLocalFile());
}

}



